package com.geek.factory.controller;

import com.geek.factory.constant.RedisImgConstant;
import com.geek.factory.service.strategy.FileUploadContext;
import com.geek.factory.constant.SuccessConstant;
import com.geek.factory.constant.MessageConstant;
import com.geek.factory.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author chenmin
 * @desc TODO
 * @date 2025/6/24
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private FileUploadContext fileUploadContext;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @PostMapping("upload")
    public Result upload(String provider , MultipartFile file) {
        String url = fileUploadContext.upload(file, provider);
        if(StringUtils.hasLength(url)){
            //将上传图片的平台信息，存储至Redis中  provider
            redisTemplate.opsForValue().set(url+"_provider" , provider);
            //将上传成功的图片信息，存储至Redis中  OSS
            redisTemplate.opsForSet().add(RedisImgConstant.UPLOAD_PIC , url);

            return new Result(SuccessConstant.SUCCESS , MessageConstant.PIC_UPLOAD_SUCCESS , url);
        }
        return new Result(SuccessConstant.FAIL , MessageConstant.PIC_UPLOAD_FAIL);
    }

    @PostMapping("delete")
    public Result delete(String provider , String url) {
        boolean flag = fileUploadContext.delete(url, provider);
        if(flag){
            return new Result(SuccessConstant.SUCCESS , MessageConstant.PIC_DELETE_SUCCESS);
        }
        return new Result(SuccessConstant.FAIL , MessageConstant.PIC_DELETE_FAIL);
    }
}
